package com.uyayo.framework.common.util.security;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 加解密类
 * @author 胡逢君
 *
 */
public class DESUtil {
	
	  private static Logger log = LoggerFactory.getLogger(DESUtil.class);

	  private static final byte[] DES_KEY_BAK = { 21, 1, -110, 82, -32, -85, -128, -65 };
	  private static final byte[] DES_KEY = "hufengjun".getBytes();
	  private static final String DES = "DES";

	  /*public static String encryptBasedDes(String data)
	  {
	    String encryptedData = null;
	    try
	    {
	      SecureRandom sr = new SecureRandom();
	      DESKeySpec deskey = new DESKeySpec(DES_KEY);

	      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
	      SecretKey key = keyFactory.generateSecret(deskey);

	      Cipher cipher = Cipher.getInstance(DES);
	      cipher.init(1, key, sr);

	      encryptedData = new BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
	      encryptedData = encryptedData.replaceAll("\r|\n","");  //排除换行
	    } catch (Exception e) {
	      log.error("加密错误，错误信息：", e);
	      throw new RuntimeException("加密错误，错误信息：", e);
	    }
	    return encryptedData;
	  }*/

	 /* public static String decryptBasedDes(String cryptData)
	  {
	    String decryptedData = null;
	    try
	    {
	      SecureRandom sr = new SecureRandom();
	      DESKeySpec deskey = new DESKeySpec(DES_KEY);

	      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
	      SecretKey key = keyFactory.generateSecret(deskey);

	      Cipher cipher = Cipher.getInstance(DES);
	      cipher.init(2, key, sr);

	      decryptedData = new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(cryptData)));
	    } catch (Exception e) {
	      log.error("解密错误，错误信息：", e);
	      throw new RuntimeException("解密错误，错误信息：", e);
	    }
	    return decryptedData;
	  }
*/
	  public static byte[] encrypt(byte[] src, byte[] key)
	    throws Exception
	  {
	    SecureRandom sr = new SecureRandom();

	    DESKeySpec dks = new DESKeySpec(key);

	    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
	    SecretKey securekey = keyFactory.generateSecret(dks);

	    Cipher cipher = Cipher.getInstance(DES);

	    cipher.init(1, securekey, sr);

	    return cipher.doFinal(src);
	  }

	 /* public static void main(String[] arg) {
	    String key = "123456";
	    String name = "胡逢君";
	    try {
	    	System.out.println(encryptBasedDes(key));
	    	System.out.println(decryptBasedDes("vL6ojBxV5/o="));
	    	System.out.println(encryptBasedDes(name));
	    	System.out.println(decryptBasedDes("ye4wgmwWieIwcuirTBXWyQ=="));
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
	}*/
}
